package cn.gok.mmall.service.impl;

import cn.gok.mmall.common.ServerResponse;
import cn.gok.mmall.dao.CategoryMapper;
import cn.gok.mmall.pojo.Category;
import cn.gok.mmall.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: chenfan
 * @Description:
 */
@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ServerResponse getCategoriesByParentId(Integer parentCategoryId) {

        if (parentCategoryId ==null){
            return ServerResponse.error("请输入类别id");
        }

        List<Category> categories = categoryMapper.getCategoriesByParentId(parentCategoryId);

        ServerResponse<List<Category>> serverResponse = ServerResponse.success(categories);
        return serverResponse;
    }


    @Override
    public ServerResponse getAllCategoriesByParentId(Integer parentCategoryId) {

        Set<Category> categorySet = new HashSet<>();
        findChildrenCategory(categorySet,parentCategoryId);

        List<Integer> categoryIds = new ArrayList<>();
        for (Category category : categorySet) {
            categoryIds.add(category.getId());
        }

        return ServerResponse.success(categoryIds);
    }


    /**
     * 此方法用来递归查出子节点
     */

    public Set<Category> findChildrenCategory(Set<Category> categorySet, Integer categoryId){

        //根据id获取当前节点的信息, 并将其存入set集合中
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if(category != null){
            categorySet.add(category);
        }

        /*
            通过递归查出给定categoryId 的节点 下的子节点列表
                    100001
                     ---->     100006
                               100007
                               100008

                               10006
                                     ---->     10000010
                                               10000012
                               100007
                                    ---->    10000017
                                             10000018
         */
        List<Category> categories = categoryMapper.getCategoriesByParentId(categoryId);

        //for结束，即为递归退出的条件
        for (Category childCategory : categories) {
            findChildrenCategory(categorySet,childCategory.getId());
        }

        return categorySet;
    }

}
